package com.ccb.course.controller;


import com.ccb.course.entity.Course;
import com.ccb.course.entity.Student;
import com.ccb.course.service.CourseService;
import com.ccb.course.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录
 */
@Controller
public class TotalController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    // 跳转首页面
    @GetMapping()
    public String getLogin(){return "course/index";}

    // 登录验证
    @PostMapping("/login")
    @ResponseBody
    public Student login(Student student){
        // 根据学生的id和password去数据库查询是否存在且密码正确
        Student student0 = studentService.selectStudentByAll(student);
        if(student0 == null){
            student0 = new Student();
        }
        student0.setPassword("123");
        return student0;
    }

    // 跳转到选课界面
    @GetMapping("/selectCourse")
    public ModelAndView getSelect(Student student){
        ModelAndView mv = new ModelAndView();
        // 储存学生no
        mv.addObject("student", student);
        mv.setViewName("course/selectCourse");
        return mv;
    }

    // 查询可选课程
    @RequestMapping("/selectCourseByNo")
    @ResponseBody
    public Map<String, Object> selectCourseByNo(int sno){
        List<Course> courses = courseService.selectCourseByNo(sno);
        Map<String, Object> map = new HashMap<>();
        map.put("rows", courses);
        map.put("code", 0);
        map.put("total", courses.size());
        return map;
    }

    // 选课提交
    @PostMapping("/selected")
    @ResponseBody
    public ModelMap selected(String nos, int sno){
        int i = courseService.selectedCourse(nos, sno);
        System.out.println(i);
        ModelMap mmap = new ModelMap();
        mmap.put("msg", "选课成功");
        return mmap;
    }

    // 跳转到当前学生所选名单
    @PostMapping("/viewSelected")
    public ModelAndView viewSelected(Student student){
        ModelAndView mv = new ModelAndView();
        // 储存学生no
        mv.addObject("student", student);
        mv.setViewName("course/viewSelected");
        return mv;
    }

    // 返回当前学生所选课名单
    @PostMapping("/viewSelectedCourse")
    @ResponseBody
    public Map<String, Object> selectSelectedCourse(int sno){
        List<Course> courses = courseService.selectSelectedCourseByNo(sno);
        Map<String, Object> map = new HashMap<>();
        map.put("rows", courses);
        map.put("code", 0);
        map.put("total", courses.size());
        return map;
    }

}

